<?php
class Router {
	var $registry;
	var $path;
	var $args = array();
	
	function Router(&$registry) {
		$this->registry = &$registry;
	}
	
	function setPath($path) {
		//$path = trim($path, '/\\');
		$path .= DIRSEP;
		if (is_dir($path) == false) {
			die('Invalid controller path: `' . $path . '`');
		}
		$this->path = $path;
	}
	
	function getController(&$file, &$controller, &$action, &$args) {
		$route = (empty($_GET['route'])) ? '' : $_GET['route'];
		if (empty($route)) { $route = 'index'; }
		
		// Get separate parts
		$route = trim($route, '/\\');
		$parts = explode('/', $route);
		
		// Find right controller
		$cmd_path = $this->path;
		foreach ($parts as $part) {
			$fullpath = $cmd_path . $part;

			// Is there a dir with this path?
			if (is_dir($fullpath)) {
				$cmd_path .= $part . DIRSEP;
				array_shift($parts);
				continue;
			}
			
			// Find the file
			if (is_file($fullpath . '.class.php')) {
				$controller = $part;
				array_shift($parts);
				break;
			}
		}
		
		if (empty($controller)) { $controller = 'index'; };
		
		// Get action
		$action = array_shift($parts);
		if (empty($action)) { $action = 'index'; }
		$file = $cmd_path . $controller . '.class.php';
		$args = $parts;
	}
	
	function delegate() {
		// Analyze route
		$this->getController($file, $controller, $action, $args);

		// File available?
		if (is_readable($file) == false) {
			die ('404 Not Found Controll');
		}

		// Include the file
		include ($file);
		
		// Initiate the class
		$class = 'Controller_' . $controller;
		$controller = new $class();
		//$controller->setRegistry($this->registry);

		// Action available?
		if (is_callable(array($controller, $action)) == false) {
			die ('404 Not Found Action');
		}
		
		// Run action
		//$controller->$action();
		$controller->execute($action);
	}
}
?>